﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Windows.Forms;
using System.IO;
using CrystalDecisions.CrystalReports.Engine;
using LPV_POS.Baocao;
using CrystalDecisions.Shared;

namespace LPV_POS.mh_pos.mh_inbaocao
{
    class mh_inA5
    {
        
        //tbBH_PHIEU_TMP.WriteXmlSchema(Application.StartupPath + "//BH_PHIEU_TMP.XSD");

        public void f_inhoadon(System.Data.DataTable __tbBH_PHIEU_TMP, System.Data.DataTable __tbBH_PHIEU_CT_TMP, Boolean _iInLai, int _iPrintOut, string sTieude,string sFooter, Boolean iMoKet)
        {
            System.Data.DataTable _tbBH_PHIEU_TMP = __tbBH_PHIEU_TMP.Copy();
            System.Data.DataTable _tbBH_PHIEU_CT_TMP = __tbBH_PHIEU_CT_TMP.Copy();
            System.Drawing.Printing.PrinterSettings cls = new System.Drawing.Printing.PrinterSettings();
            string sPrinterDefault = cls.PrinterName;
            try
            {

                #region "   Mearge _tbBH_PHIEU_CT_TMP.Rows"
                DataRow drTruoc = null;
                _tbBH_PHIEU_CT_TMP.Columns["THANH_TIEN"].Expression = "SO_LUONG * DON_GIA - CHIETKHAU_TIEN";
                if (!_tbBH_PHIEU_CT_TMP.Columns.Contains("GIA_BAN"))
                    _tbBH_PHIEU_CT_TMP.Columns.Add("GIA_BAN");
                    _tbBH_PHIEU_CT_TMP.Columns["GIA_BAN"].Expression = "DON_GIA";
                //_tbBH_PHIEU_CT_TMP.Columns["THANH_TIEN"].ReadOnly = false;
                foreach (DataRow drCT in _tbBH_PHIEU_CT_TMP.Select("MAHH NOT LIKE 'Tien_Gio%'", "MAHH, DON_GIA, CHIETKHAU_PHANTRAM"))
                {
                    if (drTruoc != null)
                    {
                        if (drCT["MAHH"] + "" == drTruoc["MAHH"] + "" &&
                            drCT["CHIETKHAU_PHANTRAM"] + "" == drTruoc["CHIETKHAU_PHANTRAM"] + ""
                            )
                        {
                            float fSL1 = 0;
                            float fSL2 = 0;

                            float fCHIETKHAU_TIEN1 = 0;
                            float fCHIETKHAU_TIEN2 = 0;
                            //float fDG1 = 0;

                            float.TryParse(drTruoc["SO_LUONG"] + "", out fSL1);
                            float.TryParse(drCT["SO_LUONG"] + "", out fSL2);

                            float.TryParse(drTruoc["CHIETKHAU_TIEN"] + "", out fCHIETKHAU_TIEN1);
                            float.TryParse(drCT["CHIETKHAU_TIEN"] + "", out fCHIETKHAU_TIEN2);

                            //float.TryParse(drTruoc["DON_GIA"] + "", out fDG1);

                            drTruoc["SO_LUONG"] = fSL2 + fSL1;
                            drTruoc["CHIETKHAU_TIEN"] = fCHIETKHAU_TIEN1 + fCHIETKHAU_TIEN2;
                            //drTruoc["THANH_TIEN"] = (fSL2 + fSL1) * fDG1;
                            _tbBH_PHIEU_CT_TMP.Rows.Remove(drCT);
                            continue;
                        }
                    }
                    drTruoc = drCT;
                }
                #endregion

                #region "   Thanh_Tien_Sau"
                float fTHANH_TIEN = 0;
                float fCK_TIEN = 0;
                float fCK_TIEN_AN = 0;
                float fCK_TIEN_UONG = 0;
                float.TryParse(_tbBH_PHIEU_TMP.Rows[0]["THANH_TIEN"] + "", out fTHANH_TIEN);
                float.TryParse(_tbBH_PHIEU_TMP.Rows[0]["CK_TIEN"] + "", out fCK_TIEN);
                float.TryParse(_tbBH_PHIEU_TMP.Rows[0]["CK_THUCAN_TIEN"] + "", out fCK_TIEN_AN);
                float.TryParse(_tbBH_PHIEU_TMP.Rows[0]["CK_THUCUONG_TIEN"] + "", out fCK_TIEN_UONG);
                _tbBH_PHIEU_TMP.Rows[0]["THANH_TIEN"] = fTHANH_TIEN;

                #region "   TONG_TIEN"
                _tbBH_PHIEU_TMP.Columns["TONG_TIEN"].Expression = "";
                _tbBH_PHIEU_TMP.Columns["TONG_TIEN"].ReadOnly = false;

                float fphuthu = 0;
                float fphuthukhac = 0;
                float fvattien = 0;
                float.TryParse(_tbBH_PHIEU_TMP.Rows[0]["PHU_THU"] + "", out fphuthu);
                float.TryParse(_tbBH_PHIEU_TMP.Rows[0]["VAT_TIEN"] + "", out fvattien);
                float.TryParse(_tbBH_PHIEU_TMP.Rows[0]["PHU_THU_KHAC"] + "", out fphuthukhac);
                _tbBH_PHIEU_TMP.Rows[0]["TONG_TIEN"] = fTHANH_TIEN - fCK_TIEN - fCK_TIEN_AN - fCK_TIEN_UONG + fphuthu + fphuthukhac + fvattien;

                #endregion

                #endregion

                DataTable tbHinh = this.Create_Datatable();
                tbHinh.TableName = "dt_hinh";
                ////tbHinh.WriteXmlSchema(Application.StartupPath + "\\dt_hinh.XSD");

                //LPV_POS.Baocao.Bill_A5 rptA5 = new LPV_POS.Baocao.Bill_A5();
                ReportDocument rptA5 = new ReportDocument();
                string sRptPath = Application.StartupPath + "\\report\\Bill_A5.rpt";

                System.IO.FileInfo fi = new FileInfo(sRptPath);
                if (!fi.Exists)
                    return;
                rptA5.Load(sRptPath, CrystalDecisions.Shared.OpenReportMethod.OpenReportByTempCopy);
                
                int ii = 1;
                float iDISC1PT = 0;
                float iDISC1TI = 0;
                float iDISC1TI_All = 0;

                
                rptA5.DataDefinition.FormulaFields["tieude"].Text = "'" + sTieude + "'";
                rptA5.DataDefinition.FormulaFields["footer"].Text = "'" + sFooter + "'";

                #region "   giam gia tien gio"
                rptA5.DataDefinition.FormulaFields["DISC1PT"].Text = "'0%'";
                #region "   lay data va xoa tiengio"
                for (int i = 0; i < _tbBH_PHIEU_CT_TMP.Select("MAHH LIKE 'Tien_Gio%'").Length; i++)
                {
                    if (i >= 0 && i <= 2)
                    {
                        float fSL = 0;
                        float fDG = 0;
                        float fTT = 0;

                        float.TryParse(_tbBH_PHIEU_CT_TMP.Select("MAHH LIKE 'Tien_Gio'")[i]["CHIETKHAU_PHANTRAM"] + "", out iDISC1PT);
                        float.TryParse(_tbBH_PHIEU_CT_TMP.Select("MAHH LIKE 'Tien_Gio'")[i]["CHIETKHAU_TIEN"] + "", out iDISC1TI);
                        iDISC1TI_All += iDISC1TI;
                        if (iDISC1PT > 0)
                            rptA5.DataDefinition.FormulaFields["DISC1PT"].Text = "'" + iDISC1PT.ToString("N0") + "%'";

                        float.TryParse(_tbBH_PHIEU_CT_TMP.Select("MAHH LIKE 'Tien_Gio'")[i]["SO_LUONG"] + "", out fSL);
                        float.TryParse(_tbBH_PHIEU_CT_TMP.Select("MAHH LIKE 'Tien_Gio'")[i]["DON_GIA"] + "", out fDG);
                        float.TryParse(_tbBH_PHIEU_CT_TMP.Select("MAHH LIKE 'Tien_Gio'")[i]["THANH_TIEN"] + "", out fTT);

                        rptA5.DataDefinition.FormulaFields["SL_K" + (ii)].Text = "'" + fSL + "'";
                        rptA5.DataDefinition.FormulaFields["DG_K" + (ii)].Text = "'" + fDG.ToString("N0") + "'";
                        rptA5.DataDefinition.FormulaFields["TT_K" + (ii++)].Text = "'" + fTT.ToString("N0") + "'";
                        //
                        //set xong thi xoa TIEN_GIO ra khoi tbBH_PHIEU_CT_TMP
                        _tbBH_PHIEU_CT_TMP.Rows.Remove(_tbBH_PHIEU_CT_TMP.Select("MAHH LIKE 'Tien_Gio'")[i--]);
                    }
                }
                #endregion

                rptA5.DataDefinition.FormulaFields["DISC1TI"].Text = "'" + iDISC1TI_All.ToString("N0") + "'";
                #endregion

                #region "   giam gia T.A; T.U; Bill"
                float iDISC2PT = 0;
                float iDISC2TI = 0;

                float iDISC2TI_All = 0;
                rptA5.DataDefinition.FormulaFields["DISC2PT"].Text = "'0%'";
                
                #region "   bo"
                //
                //foreach (DataRow dr in _tbBH_PHIEU_CT_TMP.Rows)
                //{
                //    /////////PHAN TRAM
                //    float.TryParse(dr["CHIETKHAU_PHANTRAM"] + "", out iDISC2PT);
                //    if (_tbBH_PHIEU_CT_TMP.Select("CHIETKHAU_PHANTRAM = " + iDISC2PT + "").Length == _tbBH_PHIEU_CT_TMP.Rows.Count)
                //        rptA5.DataDefinition.FormulaFields["DISC2PT"].Text = "'" + iDISC2PT.ToString("N0") + "%'";
                //    else
                //        rptA5.DataDefinition.FormulaFields["DISC2PT"].Text = "''";

                //    //////////TIEN
                //    float.TryParse(dr["CHIETKHAU_TIEN"] + "", out iDISC2TI);
                //    iDISC2TI_All += iDISC2TI;
                //}
                #endregion

                float.TryParse(_tbBH_PHIEU_TMP.Rows[0]["CK_THUCAN_PHANTRAM"] + "", out iDISC1PT);
                float.TryParse(_tbBH_PHIEU_TMP.Rows[0]["CK_THUCUONG_PHANTRAM"] + "", out iDISC2PT);
                rptA5.DataDefinition.FormulaFields["DISC2PT"].Text = "''";//99999//tam thoi chua dua % T.A, T.U vao

                float.TryParse(_tbBH_PHIEU_TMP.Rows[0]["CK_THUCAN_TIEN"] + "", out iDISC1TI);
                float.TryParse(_tbBH_PHIEU_TMP.Rows[0]["CK_THUCUONG_TIEN"] + "", out iDISC2TI);
                
                float.TryParse(_tbBH_PHIEU_TMP.Rows[0]["CK_TIEN"] + "", out iDISC2TI_All);
                rptA5.DataDefinition.FormulaFields["DISC2TI"].Text = "'" + (iDISC1TI + iDISC2TI).ToString("N0") + "'";//chi tinh thc_ko tinh tin gio
                //


                rptA5.DataDefinition.FormulaFields["DISC3TI"].Text = "'" + (iDISC2TI_All).ToString("N0") + "'";
                /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                rptA5.Database.Tables["BH_PHIEU_CT_TMP"].SetDataSource(_tbBH_PHIEU_CT_TMP);
                rptA5.Database.Tables["BH_PHIEU_TMP"].SetDataSource(_tbBH_PHIEU_TMP);
                rptA5.Database.Tables["dt_hinh"].SetDataSource(tbHinh);
                /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                #endregion
                /////////////////////////////////
                thuvien othuvien = new thuvien();
                //

                #region "   Khach hang"
                System.Data.DataTable tbDM_KHACHHANG = othuvien.SP_SelectDataTable("SP_EXECUTESQL", new string[] { "@tre_tien_do_bi_MrLong_la" }, new object[] { "SELECT * FROM DM_KHACHHANG WHERE THEKHACHHANG = '" + _tbBH_PHIEU_TMP.Rows[0]["CUSTOMER_ID"] + "'" });
                if (tbDM_KHACHHANG.Rows.Count > 0)
                {
                    rptA5.DataDefinition.FormulaFields["KH_TEN"].Text = "'" + tbDM_KHACHHANG.Rows[0]["OBJNAME"].ToString().Trim() + "'";
                    rptA5.DataDefinition.FormulaFields["KH_DIACHI"].Text = "'" + tbDM_KHACHHANG.Rows[0]["DIACHI"].ToString().Trim() + "'";
                    rptA5.DataDefinition.FormulaFields["KH_MASOTHUE"].Text = "'" + tbDM_KHACHHANG.Rows[0]["MA_SO_THUE"].ToString().Trim() + "'";
                }
                else
                {
                    rptA5.DataDefinition.FormulaFields["KH_TEN"].Text = "''";
                    rptA5.DataDefinition.FormulaFields["KH_DIACHI"].Text = "''";
                    rptA5.DataDefinition.FormulaFields["KH_MASOTHUE"].Text = "''";
                }
                #endregion
                
                #region "   cty"
                System.Data.DataTable tbDM_COMPANY = othuvien.SP_SelectDataTable("SP_EXECUTESQL", new string[] { "@gan_toi_0209_ma_chua_co_lich_nghile" }, new object[] { "SELECT * FROM DM_COMPANY" });
                rptA5.DataDefinition.FormulaFields["CTY_TEN"].Text = "'" + tbDM_COMPANY.Rows[0]["TENCONGTY"] + "'";
                rptA5.DataDefinition.FormulaFields["CTY_DIACHI"].Text = "'" + tbDM_COMPANY.Rows[0]["DIACHI"] + "'";
                rptA5.DataDefinition.FormulaFields["CTY_DIENTHOAI"].Text = "'" + tbDM_COMPANY.Rows[0]["DIENTHOAI"] + "'";
                #endregion

                #region "   tong_tien_bang_chu"
                string sTien_Chu = new cpublic().ChuyenSo_ThanhChu(_tbBH_PHIEU_TMP.Rows[0]["TONG_TIEN"] + "");
                if (sTien_Chu != "")
                    sTien_Chu = sTien_Chu.Trim() + " đồng chẵn";
                rptA5.DataDefinition.FormulaFields["tong_tien_bang_chu"].Text = "'" + sTien_Chu + "'";
                #endregion

                //int iSO_KHACH = 0;
                cpublic ocpublic = new cpublic();

                if (ocpublic.Registry_Get("chkSo_Khach_Tren_Ban") + "" == "True")
                    rptA5.DataDefinition.FormulaFields["SO_KHACH"].Text = "'" + _tbBH_PHIEU_TMP.Rows[0]["SO_KHACH"] + "'";

                if (ocpublic.Registry_Get("chkNhan_Vien_Phuc_Vu") + "" == "True")
                    rptA5.DataDefinition.FormulaFields["NHANVIEN_PHUCVU"].Text = "'" + _tbBH_PHIEU_TMP.Rows[0]["NHANVIEN_PHUCVU"] + "'";
                rptA5.DataDefinition.FormulaFields["NGAY_LAM_VIEC"].Text = "'" + _tbBH_PHIEU_TMP.Rows[0]["NGAY_LAM_VIEC"] + "'";

                #region "   PrintOptions"
                PageMargins margins = rptA5.PrintOptions.PageMargins;
                margins.bottomMargin = 0;
                margins.leftMargin = 0;
                margins.rightMargin = 0;
                margins.topMargin = 0;
                rptA5.PrintOptions.ApplyPageMargins(margins);

                rptA5.PrintOptions.PrinterName = sPrinterDefault;//rptA5.PrintOptions.PrinterName = "EPSON LQ-300+II ESC/P2";
                #endregion

                if (ocpublic.Registry_Get("chkCrystalReport_Display") + "" == "True")
                {
                    mh_View frm = new mh_View(rptA5);
                    frm.Show();
                }
                
                rptA5.PrintToPrinter(_iPrintOut, true, 1, 100);
                if (Variable.tbBH_CAU_HINH.Rows[0]["MO_KET"] + "" == "True" && iMoKet)
                    LPV_CASH_DRAWER.OpenCashDrawer(sPrinterDefault);
            }
            catch (Exception ex)
            {
                string s = ex.Message;
                MessageBox.Show(sPrinterDefault + "\n" + ex.Message, "f_inhoadon");
            }
        }

        public void f_inhoadon(string _sBAN_MA, string _sPhieu_Ma, int _iDM_BAN_DAT_BAN_ID, Boolean _iInLai, int _iPrintOut, string sTieuDe, string sFooter, Boolean iMoKet)
        {
            thuvien othuvien = new thuvien();
            int iflag = 4;//BILL - TAM TINH
            if (_iInLai)//BILL - DA THANH TOAN
                iflag += 20;

            System.Data.DataTable _tbBH_PHIEU_TMP = othuvien.SP_SelectDataTable("sp_mh_banhang",
                                                        new string[] { "@flag", "@DM_BAN_MA", "@BH_PHIEU_MA", "@DM_BAN_DAT_BAN_ID" },
                                                        new object[] { iflag, _sBAN_MA, _sPhieu_Ma, _iDM_BAN_DAT_BAN_ID });

            System.Data.DataTable _tbBH_PHIEU_CT_TMP = othuvien.SP_SelectDataTable("sp_mh_banhang",
                                                        new string[] { "@flag", "@BH_PHIEU_MA", "@DM_BAN_DAT_BAN_ID", "@DM_BAN_MA" },
                                                        new object[] { iflag + 1, _sPhieu_Ma, _iDM_BAN_DAT_BAN_ID, _sBAN_MA });

            //_tbBH_PHIEU_CT_TMP.TableName = "tbBH_PHIEU_CT_TMP";
            //_tbBH_PHIEU_CT_TMP.WriteXmlSchema(Application.StartupPath + "/BH_PHIEU_CT_TMP.XSD");

            //_tbBH_PHIEU_TMP.TableName = "BH_PHIEU_TMP";
            //string sFile = Application.StartupPath + "/BH_PHIEU_TMP.XSD";
            //_tbBH_PHIEU_TMP.WriteXmlSchema(sFile);

            this.f_inhoadon(_tbBH_PHIEU_TMP, _tbBH_PHIEU_CT_TMP, _iInLai, _iPrintOut, sTieuDe, sFooter, iMoKet);

        }

        private DataTable Create_Datatable()
        {
            DataTable dt = new DataTable();
            DataRow row;
            dt.Columns.Add("Hinh", System.Type.GetType("System.Byte[]"));
            //dt.Columns.Add("HinhDetail", System.Type.GetType("System.Byte[]"));
            row = dt.NewRow();

            //Create Filestream to read image
            FileStream fs;

            //Create variable BinaryReader to read bytes of image
            BinaryReader br;

            //Check exists of image

            if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + "logo.bmp"))
            {
                //open image in file stream
                fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "logo.bmp", FileMode.Open);
            }
            else //if image not exists show image Nopoto.img
                return dt;

            br = new BinaryReader(fs);
            byte[] b = new byte[fs.Length];
            b = br.ReadBytes(Convert.ToInt32(fs.Length));
            row["Hinh"] = b;
            //row["HinhDetail"] = b;
            dt.Rows.Add(row);
            fs.Dispose();


            return dt;
        }



        internal void f_inhoadon(string DM_BAN_MA, string BH_PHIEU_MA, int p, bool p_4, int p_5)
        {
            throw new NotImplementedException();
        }
    }
}
